local Widget = require 'widgets/widget'
local Text = require 'widgets/text'
local Image = require 'widgets/image'
local ImageButton = require 'widgets/imagebutton'
local TrueScrollArea = require "widgets/truescrollarea"

local kukude_txt = require('core_kukude/widgets/kukude_txt')
local kukude_pedia_scrollablelist = require('core_kukude/widgets/kukude_pedia_scrollablelist')

local modid = 'kukude'
local lang_pedia_keywords = require('core_kukude/languages/pedia/'..TUNING[string.upper('CONFIG_'..modid..'_LANG')]).pedia_keywords
local data_kukude_pedia = require('core_kukude/data/pedia')
local data_kukude_pedia_ios = data_kukude_pedia.ios
local data_kukude_pedia_ios_orders = data_kukude_pedia.ios_orders
local data_ios = require('core_kukude/data/insertobjs')

local max_hud_scale_root = .75
local root_bg_scale = .75

---@class widget_kukude_pedia : widget_widget
---@field root widget_widget # root
---@field bg widget_image # bg
---@field scroll_page_member table<string,widget_imagebutton[]> # 滚动条成员(自动布局)
---@field ios_scroll_list widget_scrollablelist # ios scroll list
---@field item_root widget_widget # 图鉴容器
---@field item_avatar_bg widget_image # 头像背景
---@field item_avatar widget_image # 头像
---@field item_label widget_text # 图鉴名字
---@field item_recipe_title widget_text # 图鉴 配方title
---@field item_recipe {avatar_bg:widget_image,avatar:widget_image,num:widget_text,name:widget_text}[]
---@field item_unlock_neccessary_title widget_text # 图鉴 解锁条件title
---@field item_unlock_avatar widget_image # 图鉴 解锁条件头像
---@field item_unlock_details widget_text # 图鉴 解锁条件详情
---@field item_others_scrollarea_txt_width number # 图鉴其他滚动条文本宽度
---@field item_others_scrollarea_txt widget_text # 图鉴其他滚动条文本
---@field scrollarea widget_truescrollarea # 图鉴滚动区域
local kukude_pedia = Class(Widget,
---@param self widget_kukude_pedia
function(self)
    Widget._ctor(self, 'kukude_pedia')

    -- root
    self.root = self:AddChild(Widget('root'))
    self.root:SetVAnchor(ANCHOR_MIDDLE)
    self.root:SetHAnchor(ANCHOR_MIDDLE)
    self.root:SetScaleMode(SCALEMODE_FIXEDPROPORTIONAL)
    self.root:SetMaxPropUpscale(max_hud_scale_root)

    -- pedia background
    self.bg = self.root:AddChild(Image('images/pedia/bg.xml','bg.tex'))
    self.bg:SetScale(root_bg_scale,root_bg_scale,root_bg_scale)

    -- scroll members
    self.scroll_page_member = {}
    self.scroll_page_member.ios = {}

    for i,v in ipairs(data_kukude_pedia_ios_orders) do
        local _xml = 'images/inventoryimages/'..v..'.xml'
        local _tex = v..'.tex'

        if data_ios[v].noimg then
            _xml = 'images/inventoryimages/io_rabbitleg.xml'
            _tex = 'io_rabbitleg.tex'
        end

        ---@type widget_imagebutton
        local member_bg = ImageButton('images/pedia/oneitem_list_bg.xml','oneitem_list_bg.tex','oneitem_list_bg.tex','oneitem_list_bg.tex','oneitem_list_bg.tex','oneitem_list_bg.tex')
        ---@type widget_image
        local member_slot_bg = member_bg:AddChild(Image('images/pedia/inv_slot.xml','inv_slot.tex'))
        ---@type widget_image
        local member_avatar = member_slot_bg:AddChild(Image(_xml,_tex))
        ---@type widget_text
        local member_label = member_bg:AddChild(Text(BODYTEXTFONT,30,data_kukude_pedia_ios[v].name))

        member_slot_bg:SetScale(.65,.65,1)
        member_slot_bg:SetPosition(-100-70/2+20,0,0)
        member_label:SetRegionSize(100+70,40)
        member_label:SetHAlign(ANCHOR_LEFT)
        member_label:SetPosition(20,0)

        ---@type widget_image
        local member_lock = member_avatar:AddChild(Image('images/pedia/lock.xml','lock.tex'))
        member_lock:SetScale(.3,.44)
        member_lock:SetPosition(24,24)

        local member_label_rgba = data_kukude_pedia_ios[v].name_color
        if member_label_rgba then
            member_label:SetColour(unpack(member_label_rgba))
        end

        member_bg:SetOnClick(function ()
            self:SwitchItem(v, _xml, _tex)
        end)

        self.scroll_page_member.ios[i] = member_bg
        ---@diagnostic disable-next-line: inject-field
        self.scroll_page_member.ios[i].lock_png = member_lock
    end

    -- 滚动条
    local SCROLLBAR_STYLE = {
        unique = 'kukude_pedia',
        atlas = "images/pedia/scrollbar.xml",
        up = "up.tex",
        down = "down.tex",
        bar = "bar.tex",
        handle = "handle.tex",
        --~ scale = 0.4,
        scale = 0.5,
    }

    local groups_order = {'ios'}
    ---@type widget_scrollablelist
    self.ios_scroll_list = self.root:AddChild(kukude_pedia_scrollablelist(groups_order,200,450,50,10,nil,nil,nil,nil,nil,nil,nil,nil,SCROLLBAR_STYLE,self.scroll_page_member))
    self.ios_scroll_list.scroll_bar_line:SetScale(.8,1,1)
    self.ios_scroll_list:SetPosition(-120,0,0)

    -- 图鉴容器
    self.item_root = self.root:AddChild(Widget('item_root'))
    self.item_root:SetPosition(200,0)
    -- 图鉴头像背景
    self.item_avatar_bg = self.item_root:AddChild(Image('images/pedia/inv_slot.xml','inv_slot.tex'))
    self.item_avatar_bg:SetPosition(-90,160)
    self.item_avatar_bg:SetScale(1.7,1.7)
    self.item_avatar_bg:Hide()
    -- 图鉴头像
    self.item_avatar = self.item_avatar_bg:AddChild(Image())
    -- 图鉴名字
    self.item_label = self.item_root:AddChild(Text(BODYTEXTFONT,35,''))
    -- self.item_label:SetVAlign(ANCHOR_MIDDLE)
    -- self.item_label:SetHAlign(ANCHOR_LEFT)
    self.item_label:SetPosition(-90,230)
    -- self.item_label:SetRegionSize(170,35)
    -- recipe title
    self.item_recipe_title = self.item_root:AddChild(Text(CHATFONT_OUTLINE,35,lang_pedia_keywords.recipe))
    self.item_recipe_title:SetPosition(100+20,220)
    self.item_recipe_title:Hide()
    -- 生成配方
    self.item_recipe = {}

    -- 解锁条件title
    self.item_unlock_neccessary_title = self.item_root:AddChild(Text(CHATFONT_OUTLINE,35,lang_pedia_keywords.unlock_neccessary))
    self.item_unlock_neccessary_title:SetPosition(-90,70)
    self.item_unlock_neccessary_title:Hide()
    -- 解锁条件头像
    self.item_unlock_avatar = self.item_root:AddChild(Image())
    self.item_unlock_avatar:SetPosition(-90,25)
    self.item_unlock_avatar:SetScale(.5,.5)
    self.item_unlock_avatar:Hide()
    -- 解锁条件详情
    self.item_unlock_details = self.item_root:AddChild(kukude_txt(BODYTEXTFONT,28,''))
    self.item_unlock_details:SetVAlign(ANCHOR_TOP)
    self.item_unlock_details:SetHAlign(ANCHOR_LEFT)
    self.item_unlock_details:SetPosition(100,30)
    self.item_unlock_details:SetRegionSize(260,100)
    self.item_unlock_details:Hide()
    -- 滚动区域
    local area_root = self.item_root:AddChild(Widget('area_root'))
    local sub_root = self.item_root:AddChild(Widget('sub_root'))
    local width = 340
    local height = 2000
    local max_visible_height = 200
    local padding = 0
    local height_per_scroll = 23 * 1 -- 每次滚动高度
    self.item_others_scrollarea_txt_width = width-20
    local item_others_scrollarea_txt_height = 2000
    local item_others_scrollarea_txt_fontsize = 25
    self.item_others_scrollarea_txt = sub_root:AddChild(kukude_txt(BODYTEXTFONT,item_others_scrollarea_txt_fontsize,''))
    self.item_others_scrollarea_txt:SetHAlign(ANCHOR_LEFT)
    self.item_others_scrollarea_txt:SetVAlign(ANCHOR_TOP)
    self.item_others_scrollarea_txt:SetRegionSize(self.item_others_scrollarea_txt_width,item_others_scrollarea_txt_height)

    local top = math.min(height, max_visible_height)/2 - padding

    local scissor_data = {x = 0, y = -max_visible_height/2, width = width, height = max_visible_height}
    local context = {widget = sub_root, offset = {x = width/2, y = top-item_others_scrollarea_txt_height/2}, size = {w = width, height = height + padding}}
    local scrollbar = { scroll_per_click = height_per_scroll }

    self.scrollarea = area_root:AddChild(TrueScrollArea(context, scissor_data, scrollbar))
    self.scrollarea:SetPosition(-150,-130)
    self.scrollarea:Hide()
end)

function kukude_pedia:ShowPedia()
    if not self.shown then
        self:Show()
        for i,v in ipairs(data_kukude_pedia_ios_orders) do
            local know_recipe = ThePlayer.replica.builder and ThePlayer.replica.builder:KnowsRecipe(v) or false
            if know_recipe then
                ---@diagnostic disable-next-line: undefined-field
                self.scroll_page_member.ios[i].lock_png:Hide()
            else
                ---@diagnostic disable-next-line: undefined-field
                self.scroll_page_member.ios[i].lock_png:Show()
            end
        end
    end
end

function kukude_pedia:HidePedia()
    if self.shown then
        self:Hide()
    end
end

---点击列表的元素
---@param id any
---@param xml any
---@param tex any
function kukude_pedia:SwitchItem(id,xml,tex)
    -- 显示图鉴头像背景
    if not self.item_avatar_bg.shown then
        self.item_avatar_bg:Show()
    end
    -- 更新头像
    self.item_avatar:SetTexture(xml,tex)
    -- 更新名字
    self.item_label:SetString(data_kukude_pedia_ios[id].name)
    -- 更新color
    local member_label_rgba = data_kukude_pedia_ios[id].name_color
    if member_label_rgba then
        self.item_label:SetColour(unpack(member_label_rgba))
    end
    -- 显示配方title
    if not self.item_recipe_title.shown then
        self.item_recipe_title:Show()
    end
    -- 重新生成配方
    self:MakeRecipe(id)
    -- 显示解锁条件title
    if not self.item_unlock_neccessary_title.shown then
        self.item_unlock_neccessary_title:Show()
    end
    -- 更新解锁条件头像
    local unlock_prefab_id = data_kukude_pedia_ios[id].unlock_prefab_id
    if unlock_prefab_id then
        local xml_scrapbook = GetScrapbookIconAtlas(unlock_prefab_id..'.tex')
        if xml_scrapbook then
            self.item_unlock_avatar:SetTexture(xml_scrapbook,unlock_prefab_id..'.tex')
            if not self.item_unlock_avatar.shown then
                self.item_unlock_avatar:Show()
            end
        end
    else
        if self.item_unlock_avatar.shown then
            self.item_unlock_avatar:Hide()
        end
    end
    -- 更新解锁条件详情
    local unlock_info = data_kukude_pedia_ios[id].unlock
    unlock_info = SUGAR_kukude:limitMultiLineStringSingleLineMaxLen(unlock_info,14)
    self.item_unlock_details:SetMultilineTruncatedString(unlock_info,5,260,nil,nil,false,16,'\n')
    if not self.item_unlock_details.shown then
        self.item_unlock_details:Show()
    end
    -- 更新显示滚动区域
    if not self.scrollarea.shown then
        self.scrollarea:Show()
    end
    local fixed_content = SUGAR_kukude:limitMultiLineStringSingleLineMaxLen(data_kukude_pedia_ios[id].others,20)
    local num_lines = self.item_others_scrollarea_txt:SetMultilineTruncatedString(fixed_content,100,self.item_others_scrollarea_txt_width,nil,nil,false,16,'\n')
    if num_lines then
        local real_height = num_lines * 25 + 30
        self.scrollarea.scroll_pos_end = math.max(0,real_height - 200)
    end
    self.scrollarea:ResetScroll()
end

---生成配方
---@param id string
function kukude_pedia:MakeRecipe(id)
    for k,_ in pairs(self.item_recipe) do
        if self.item_recipe[k].avatar_bg then
            self.item_recipe[k].avatar_bg:Kill()
            self.item_recipe[k].avatar_bg = nil
        end
        if self.item_recipe[k].avatar then
            self.item_recipe[k].avatar:Kill()
            self.item_recipe[k].avatar = nil
        end
        if self.item_recipe[k].name then
            self.item_recipe[k].name:Kill()
            self.item_recipe[k].name = nil
        end
        if self.item_recipe[k].num then
            self.item_recipe[k].num:Kill()
            self.item_recipe[k].num = nil
        end
        self.item_recipe[k] = nil
    end
    local recipe = data_ios[id].ingres
    local count = 0
    for ingredient,num in pairs(recipe) do
        local _xml,_tex

        local ingre_is_ios = data_kukude_pedia_ios[ingredient] and true or false
        if ingre_is_ios then
            if data_ios[ingredient].noimg then
                _xml = 'images/inventoryimages/io_rabbitleg.xml'
                _tex = 'io_rabbitleg.tex'
            else
                _xml = 'images/inventoryimages/'..ingredient..'.xml'
                _tex = ingredient..'.tex'
            end
        else
            _tex = ingredient..'.tex'
            _xml = GetInventoryItemAtlas(_tex)
        end

        if _tex and _xml then
            count = count + 1
            local index = count
            self.item_recipe[index] = {}
            -- local xpos,ypos = 80,184-47*(index-1)
            -- local xpos,ypos = 20+(index-1)*42,184
            self.item_recipe[index].avatar_bg = self.item_root:AddChild(Image('images/pedia/ingredient_bg.xml','ingredient_bg.tex'))
            self.item_recipe[index].avatar_bg:SetScale(.3,.3)
            -- self.item_recipe[index].avatar_bg:SetPosition(xpos,ypos)

            self.item_recipe[index].avatar = self.item_recipe[index].avatar_bg:AddChild(Image(_xml,_tex))
            self.item_recipe[index].avatar:SetScale(1.8,1.8)

            self.item_recipe[index].num = self.item_recipe[index].avatar:AddChild(Text(NUMBERFONT, 42, 'x'..tostring(num)))
            self.item_recipe[index].num:SetPosition(0,-20)

            self.item_recipe[index].name = self.item_recipe[index].avatar:AddChild(Text(BODYTEXTFONT, 50, (STRINGS.NAMES[string.upper(ingredient)] or '')))
            -- self.item_recipe[index].name:SetRegionSize(120,30)
            -- self.item_recipe[index].name:SetHAlign(ANCHOR_LEFT)
            self.item_recipe[index].name:SetPosition(0,-60)
            self.item_recipe[index].name:Hide()

            self.item_recipe[index].avatar:SetOnGainFocus(function ()
                if not self.item_recipe[index].name.shown then
                    self.item_recipe[index].name:Show()
                end
            end)

            self.item_recipe[index].avatar:SetOnLoseFocus(function()
                if self.item_recipe[index].name.shown then
                    self.item_recipe[index].name:Hide()
                end
            end)
        end
    end

    local x_middle_pos,y_pos,avatar_width,interval = 115+20,184,38,5
    local x_stgart_pos = count%2 == 0 and (x_middle_pos - interval/2 - avatar_width*count/2 - interval*(count/2-1)) or (x_middle_pos - avatar_width/2 - (avatar_width+interval)*(count-1)/2)
    for i,_ in ipairs(self.item_recipe) do
        self.item_recipe[i].avatar_bg:SetPosition(x_stgart_pos + (i-1)*avatar_width + (i-1)*interval,y_pos)
    end

end


return kukude_pedia